import {
  getTakeAwayShopById,
  getTakeAwayShopAll,
  getTakeAwayShopPageList,
  commonUpdate,
  updateTakeAwayShop,
  addTakeAwayShop,
  deleteTakeAwayShop
} from '@/services/takeAwayShopService';
import { PageContainer } from '@ant-design/pro-layout';
import type { ProColumns, ActionType } from '@ant-design/pro-table';
import ProTable from '@ant-design/pro-table';
import { Button, Divider, message, Popconfirm, Space, Typography } from 'antd';
import React, { useRef, useState } from 'react';
import UpdateModal from '../list/components/updateModal';
import './index.less';
import { getCookie } from '@/utils/cookieUtils';

/**
 *
 * @constructor
 */
const TakeAwayShopPage: React.FC<unknown> = () => {
  const [isOpenConfig, setIsOpenConfig] = useState<boolean>(false);
  const [updateData, setUpdateData] = useState<TakeAwayShopType.TakeAwayShop>(
    {} as TakeAwayShopType.TakeAwayShop,
  );
  const actionRef = useRef<ActionType>();

  /**
   *
   * @param
   */
  const doDelete = async (model: TakeAwayShopType.TakeAwayShop) => {
    const hide = message.loading('正在删除');
    if (!model?.Id) {
      return;
    }
    try {
      await deleteTakeAwayShop({
        id: model.Id,
      });
      message.success('操作成功');
      actionRef.current?.reload();
    } catch (e: any) {
      message.error('操作失败，' + e.message);
    } finally {
      hide();
    }
  };

  /**
   *
   */
  const columns: ProColumns<TakeAwayShopType.TakeAwayShop>[] = [
    {
      title: 'id',
      dataIndex: 'Id',
      hideInSearch: true
    },

    {
      title: '门店名称',
      dataIndex: 'Name'
    },

    {
      title: '门店Logo',
      dataIndex: 'ImgUrl',
      hideInSearch: true,
      render(dom, entity) {
        return <img style={{ width: "50px", height: "50px" }} src={entity.ImgUrl} />
      },
    },
    {
      title: '电话',
      dataIndex: 'TelNumber',
      hideInSearch: true
    },
    {
      title: '门店地址',
      dataIndex: 'Address'
    },
    {
      title: '门店描述',
      dataIndex: 'Description',
      hideInSearch: true
    },
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      render: (_: any, record: any) => (
        <Space split={<Divider type="vertical" />}>
          <Typography.Link
            onClick={() => {
              setUpdateData(record);
              setIsOpenConfig(true);
            }}
          >
            修改
          </Typography.Link>
          <Popconfirm
            title="您确定要删除么？"
            onConfirm={() => doDelete(record)}
            okText="确认"
            cancelText="取消"
          >
            <Typography.Link type="danger">删除</Typography.Link>
          </Popconfirm>
        </Space>
      ),
    },
  ];

  return (
    <>
      <PageContainer>
        <ProTable<TakeAwayShopType.TakeAwayShop>
          headerTitle="管理"
          actionRef={actionRef}
          rowKey="id"
          search={{
            labelWidth: 'auto',
            defaultCollapsed: false,
          }}
          toolBarRender={() => [
          ]}
          request={async (params: any, sorter: any) => {
            const searchParams: PageInfo.PageRequest = {
              pageSize: params.pageSize,
              current: params.current
            };

            let sortQuery = "", filterQuery = `eq(Id,${getCookie("shopId")})`;
            // eslint-disable-next-line guard-for-in
            for (const key in sorter) {
              sortQuery += `${key}|${sorter[key]}`;
            }

            if (sortQuery != "") {
              searchParams['@sort'] = sortQuery;
            }

            for (const key in params) {
              if (key !== "pageSize" && key !== "current") {
                if (params[key] != "") {
                  filterQuery += `contains(${key},${params[key]})&`;
                  params[key] = '';
                }
              }
            }

            if (filterQuery != "") {
              searchParams['@filter'] = filterQuery;
            }

            searchParams['@relationships'] = "UserInfo";
            const { Items, StatusCode } = await getTakeAwayShopPageList(searchParams);
            return {
              data: Items[0]?.Records || [],
              success: StatusCode === 200,
              total: Items[0].Total,
            } as any;
          }}
          columns={columns}
        />
      </PageContainer>

      <UpdateModal initImgUrl={updateData ? updateData.ImgUrl : ""} id={updateData?.Id} closeEvent={setIsOpenConfig} isOpen={isOpenConfig} onSubmit={() => { setIsOpenConfig(false); actionRef.current?.reload(); }} />
    </>
  );
};

export default TakeAwayShopPage;
